<template>
  <div class="purchase-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.productName" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="采购人">
          <el-input v-model="searchForm.buyer" placeholder="请输入采购人" clearable />
        </el-form-item>
        <el-form-item label="入库状态">
          <el-select v-model="searchForm.status" placeholder="请选择入库状态" clearable>
            <el-option label="已入库" value="1" />
            <el-option label="未入库" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="采购时间">
          <el-date-picker
            v-model="searchForm.buyDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="operation-container">
      <el-button type="primary" @click="openEditDialog()">
        <el-icon><ShoppingCart /></el-icon> 新增采购单
      </el-button>
      <el-button type="warning" @click="handleExport">
        <el-icon><Download /></el-icon> 导出数据
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table :data="purchaseList" border v-loading="loading" class="custom-table">
      <el-table-column prop="id" label="编号" width="70" align="center" />
      <el-table-column prop="warehouseName" label="仓库名" width="120" align="center" />
      <el-table-column prop="productName" label="商品名" min-width="180" align="center" />
      <el-table-column prop="planCount" label="预计采购数量" width="120" align="center" />
      <el-table-column prop="actualCount" label="实际采购数量" width="120" align="center" />
      <el-table-column prop="buyer" label="采购人" width="100" align="center" />
      <el-table-column prop="buyDate" label="采购时间" width="120" align="center" />
      <el-table-column prop="buyerPhone" label="采购人电话" width="120" align="center" />
      <el-table-column prop="status" label="入库状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.status === '0' || row.status === 0" type="danger" effect="plain">
            {{ "未入库" }}
          </el-tag>
          <el-tag v-if="row.status === '1' || row.status === 1" type="success" effect="plain">
            {{ "已入库" }}
          </el-tag>
          <el-tag v-if="row.status === '2' || row.status === 2" type="warning" effect="plain">
            {{ "已出库" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="{ row }">
          <template v-if="row.status !== '1' && row.status !== 1">
            <template v-if="row.actualCount <= 0">
              <el-button-group>
                <el-button type="primary" link @click="openEditDialog(row)">编辑</el-button>
                <el-button type="danger" link @click="onDelete(row)">删除</el-button>
              </el-button-group>
            </template>
            <template v-else>
              <el-button v-if="row.status === '0' || row.status === 0" type="primary" link @click="openStockDialog(row)">入库</el-button>
            </template>
          </template>
          <template v-else>
            <el-button v-if="row.status === '1' || row.status === 1" type="primary" link @click="openStockDialog(row)">出库</el-button>
        </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑采购单对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editForm.id ? '编辑采购单' : '新增采购单'"
      width="600px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <div class="form-item-row">
          <div class="form-item">
            <div class="form-label"><span class="required">*</span> 仓库名</div>
            <el-select
              v-model="editForm.warehouseId"
              placeholder="请选择仓库"
              class="form-input"
              :disabled="!!editForm.id"
            >
              <template v-for="item in warehouseList" :key="item.id">
                <el-option :label="item.name" :value="item.id" />
              </template>
            </el-select>
          </div>
          <div class="form-item">
            <div class="form-label"><span class="required">*</span> 商品名</div>
            <el-select
              v-model="editForm.productId"
              placeholder="请选择商品"
              class="form-input"
              filterable
              remote
              :remote-method="getProductMethod"
              :disabled="!!editForm.id"
            >
              <template v-for="item in productList" :key="item.id">
                <el-option :label="item.name" :value="item.id" />
              </template>
            </el-select>
          </div>
        </div>

        <div class="form-item-row">
          <div class="form-item">
            <div class="form-label"><span class="required">*</span> 预计采购数量</div>
            <el-input-number v-model="editForm.planCount" :min="0" controls-position="right" style="width: 100%" />
          </div>
          <div class="form-item">
            <div class="form-label"><span class="required">*</span> 实际采购数量</div>
            <el-input-number v-model="editForm.actualCount" :min="0" controls-position="right" style="width: 100%" />
          </div>
        </div>

        <div class="form-item-row">
          <div class="form-item">
            <div class="form-label"><span class="required">*</span> 采购人</div>
            <el-input v-model="editForm.buyer" placeholder="请输入采购人" class="form-input" />
          </div>
          <div class="form-item">
            <div class="form-label"><span class="required">*</span> 采购人电话</div>
            <el-input v-model="editForm.buyerPhone" placeholder="请输入采购人电话" class="form-input" />
          </div>
        </div>

        <div class="form-item-row">
          <div class="form-item full-width">
            <div class="form-label"><span class="required">*</span> 采购时间</div>
            <el-date-picker
              v-model="editForm.buyDate"
              type="date"
              placeholder="请选择采购时间"
              class="form-input"
              format="YYYY年MM月DD日"
              value-format="YYYY-MM-DD"
            />
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false" class="cancel-button">取 消</el-button>
          <el-button type="primary" @click="submitEdit" :loading="submitLoading" class="confirm-button"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 生成入库单对话框 -->
    <el-dialog v-model="stockDialogVisible" title="入库" width="600px" destroy-on-close :close-on-click-modal="false">
      <div class="dialog-content">
        <div class="form-item-row">
          <div class="form-item full-width">
            <div class="form-label">商品名</div>
            <el-input v-model="stockForm.productName" readonly class="form-input" />
          </div>
        </div>

        <div class="form-item-row">
          <div class="form-item full-width">
            <div class="form-label">实际采购数量</div>
            <el-input v-model="stockForm.actualCount" readonly class="form-input">
              <template #append>件</template>
            </el-input>
          </div>
        </div>

        <div class="form-item-row">
          <div class="form-item full-width">
            <div class="form-label">仓库名</div>
            <el-input v-model="stockForm.warehouseName" readonly class="form-input" />
          </div>
        </div>

        <div class="form-item-row">
          <div class="form-item full-width">
            <div class="form-label">备注</div>
            <el-input v-model="stockForm.remark" class="form-input" />
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="stockDialogVisible = false" class="cancel-button">取 消</el-button>
          <el-button type="primary" @click="submitStock" :loading="submitLoading" class="confirm-button"
            >确认入库</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ShoppingCart, Edit, Delete, Finished, Download } from "@element-plus/icons-vue";
import { getProductStockList, updateProductStockRecord, addPurchaseOrder, editPurchaseOrder } from "@/api/productStock";
import { getPurchaseListExcel } from "@/api/export";
import { getWarehouseList, getProductList } from "@/api/common";

// 页面状态
const loading = ref(false);
const submitLoading = ref(false);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);

// 搜索表单
const searchForm = reactive({
  productName: "",
  buyer: "",
  status: "",
  buyDate: [],
});

// 表格数据
const purchaseList = ref([]);

// 对话框状态
const editDialogVisible = ref(false);
const stockDialogVisible = ref(false);

// 表单数据
const editForm = reactive({});
const stockForm = reactive({});

const warehouseList = ref([]);
const productList = ref([]);

// 获取采购列表数据
async function fetchPurchaseList() {
  loading.value = true;
  try {
    // 处理日期范围
    const dateRange =
      searchForm.buyDate && searchForm.buyDate.length === 2
        ? [formatDate(searchForm.buyDate[0]), formatDate(searchForm.buyDate[1])]
        : undefined;

    const res = await getProductStockList({
      productName: searchForm.productName || undefined,
      buyer: searchForm.buyer || undefined,
      status: searchForm.status || undefined,
      startDate: dateRange ? dateRange[0] : undefined,
      endDate: dateRange ? dateRange[1] : undefined,
      current: currentPage.value,
      size: pageSize.value,
    });

    console.log("API响应数据:", res);

    if (res && res.data) {
      purchaseList.value = Array.isArray(res.data.list) ? res.data.list : [];
      total.value = res.data.total || 0;
    } else {
      purchaseList.value = [];
      total.value = 0;
      ElMessage.warning("未获取到采购数据");
    }
  } catch (error) {
    console.error("获取采购数据失败:", error);
    ElMessage.error("获取采购数据失败，请稍后重试");
    purchaseList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

// 搜索处理
function handleSearch() {
  currentPage.value = 1; // 重置到第一页
  fetchPurchaseList();
}

// 重置搜索
function resetSearch() {
  // 重置搜索表单
  Object.assign(searchForm, {
    productName: "",
    buyer: "",
    status: "",
    buyDate: [],
  });
  currentPage.value = 1;
  fetchPurchaseList();
}

// 分页大小变化
function handleSizeChange(newSize) {
  pageSize.value = newSize;
  fetchPurchaseList();
}

// 页码变化
function handleCurrentChange(newPage) {
  currentPage.value = newPage;
  fetchPurchaseList();
}

// 导出功能
async function handleExport() {
  await getPurchaseListExcel();
  ElMessage.success("导出成功");
}

// 打开编辑对话框
async function openEditDialog(row) {
  await fetchWarehouseList();
  if (row) {
    // 编辑模式：深拷贝避免直接修改表格数据
    Object.assign(editForm, JSON.parse(JSON.stringify(row)));
  } else {
    // 新增模式：重置表单
    Object.assign(editForm, {
      id: undefined,
      warehouseId: "",
      productId: "",
      planCount: 0,
      actualCount: 0,
      buyer: "",
      buyDate: "",
      buyerPhone: "",
      status: 0, // 默认未入库
    });
  }
  editDialogVisible.value = true;
}

// 提交编辑
async function submitEdit() {
  // 表单验证
  const validationErrors = validateEditForm();

  if (validationErrors.length > 0) {
    ElMessage.error(validationErrors[0]);
    return;
  }
  submitLoading.value = true;
  const isUpdate = editForm.id;
  const res = await (isUpdate ? editPurchaseOrder(editForm) : addPurchaseOrder(editForm));
  if (res.success) {
    if (isUpdate) {
      ElMessage.success("更新成功");
    } else {
      ElMessage.success("添加成功");
    }
    fetchPurchaseList(); // 刷新采购列表
  }
  submitLoading.value = false;
  editDialogVisible.value = false;
}

// 验证编辑表单
function validateEditForm() {
  const errors = [];

  if (!editForm.warehouseId) errors.push("请选择仓库");
  if (!editForm.productId) errors.push("请选择商品");

  if (editForm.planCount === undefined || editForm.planCount === null || editForm.planCount === "") {
    errors.push("请输入预计采购数量");
    editForm.planCount = 0;
  }

  if (editForm.actualCount === undefined || editForm.actualCount === null || editForm.actualCount === "") {
    errors.push("请输入实际采购数量");
    editForm.actualCount = 0;
  }

  if (!editForm.buyer) errors.push("请输入采购人");
  if (!editForm.buyDate) errors.push("请选择采购时间");
  if (!editForm.buyerPhone) errors.push("请输入采购人电话");

  return errors;
}

// 删除操作
function onDelete(row) {
  ElMessageBox.confirm(`确定要删除该采购单吗？删除后无法恢复`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      try {
        // 模拟删除操作
        const index = purchaseList.value.findIndex((item) => item.id === row.id);
        if (index !== -1) {
          purchaseList.value.splice(index, 1);
          ElMessage.success("删除成功");
        } else {
          ElMessage.warning("未找到要删除的记录");
        }
      } catch (error) {
        ElMessage.error("删除失败，请重试");
        console.error(error);
      }
    })
    .catch(() => {});
}

// 打开入库对话框
function openStockDialog(row) {
  Object.assign(stockForm, JSON.parse(JSON.stringify(row)));
  stockForm.remark = "";
  stockDialogVisible.value = true;
}

// 提交入库
async function submitStock() {
  submitLoading.value = true;
  const res = await updateProductStockRecord({
    productStockId: stockForm.id,
    productId: stockForm.productId,
    warehouseId: stockForm.warehouseId,
    quantity: stockForm.actualCount,
    status: stockForm.status === 0 ? 1 : 2,
    remark: stockForm.remark,
  });
  if (res.success) {
    fetchPurchaseList();
    ElMessage.success("入库成功");
    stockDialogVisible.value = false;
  } else {
    ElMessage.warning("入库失败");
  }
  submitLoading.value = false;
}

// 日期格式化
function formatDate(date) {
  if (!date) return "";
  if (typeof date === "string") return date;

  try {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  } catch (error) {
    console.error("日期格式化错误:", error);
    return "";
  }
}

const fetchWarehouseList = async () => {
  const res = await getWarehouseList();
  if (res.success) {
    warehouseList.value = res.data;
  } else {
    ElMessage.error(res.message);
  }
};

let lastCallTime = 0;
const getProductMethod = async (name) => {
  if (name === "") return;
  const now = Date.now();
  // 如果距离上次调用时间小于1000ms，则忽略本次调用
  if (now - lastCallTime < 1000) return;
  lastCallTime = now;

  const res = await getProductList(name);
  if (res.success) {
    productList.value = res.data;
  } else {
    ElMessage.error(res.message);
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchPurchaseList();
  fetchWarehouseList();
});
</script>

<style scoped>
.purchase-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.search-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-card :deep(.el-card__body) {
  padding: 16px;
}

.operation-container {
  margin-bottom: 16px;
  display: flex;
  gap: 12px;
}

.operation-container .el-button {
  padding: 10px 16px;
  font-weight: 500;
}

.operation-container .el-icon {
  margin-right: 6px;
  font-size: 16px;
}

.custom-table {
  margin-bottom: 16px;
  border-radius: 8px;
  overflow: hidden;
}

.custom-table :deep(.el-table__header) {
  background-color: #f5f7fa;
}

.custom-table :deep(.el-table__row) {
  height: 50px;
}

.custom-table :deep(.el-button--link) {
  padding: 4px 8px;
  font-size: 14px;
}

.custom-table :deep(.el-button--link .el-icon) {
  margin-right: 4px;
}

.custom-table :deep(.el-tag) {
  height: 24px;
  line-height: 22px;
  border-radius: 2px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination-container :deep(.el-pagination) {
  padding: 0;
  margin: 0;
}

.pagination-container :deep(.el-pagination .el-select .el-input) {
  width: 100px;
}

/* 对话框内容样式 */
.dialog-content {
  padding: 30px 20px;
}

.form-item-row {
  display: flex;
  margin-bottom: 24px;
  gap: 20px;
}

.form-item {
  flex: 1;
  position: relative;
}

.form-item.full-width {
  width: 100%;
}

.form-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.form-label .required {
  color: #f56c6c;
  margin-right: 4px;
}

.form-input {
  width: 100%;
}

.number-input-container {
  display: flex;
  align-items: center;
  position: relative;
}

.number-input-container .el-input-number {
  width: 100%;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 4px;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  border-top: 1px solid #f0f0f0;
}

/* 按钮样式 */
.dialog-footer {
  text-align: right;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.dialog-footer .el-button {
  margin-left: 0;
}

/* 覆盖Element Plus按钮样式 */
:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-button--primary) {
  --el-button-bg-color: #409eff;
  --el-button-border-color: #409eff;
  --el-button-hover-bg-color: #66b1ff;
  --el-button-hover-border-color: #66b1ff;
  --el-button-active-bg-color: #3a8ee6;
  --el-button-active-border-color: #3a8ee6;
}

:deep(.el-button--danger) {
  --el-button-bg-color: #f56c6c;
  --el-button-border-color: #f56c6c;
  --el-button-hover-bg-color: #f78989;
  --el-button-hover-border-color: #f78989;
  --el-button-active-bg-color: #dd6161;
  --el-button-active-border-color: #dd6161;
}

/* 输入框样式 */
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  height: 40px;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
}

/* 自定义数字输入框 */
.custom-number-input {
  position: relative;
  width: 100%;
  display: flex;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  height: 40px;
  background-color: white;
}

.custom-number-input.readonly {
  background-color: #f5f7fa;
}

.number-input {
  flex: 1;
  border: none;
  padding: 0 12px;
  height: 100%;
  outline: none;
  background: transparent;
  font-size: 14px;
}

.number-input::-webkit-inner-spin-button,
.number-input::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.number-controls {
  display: flex;
  flex-direction: column;
  border-left: 1px solid #dcdfe6;
  width: 72px;
}

.number-up,
.number-down {
  height: 50%;
  border: none;
  background-color: #f5f7fa;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
  font-size: 14px;
  padding: 0;
}

.number-up {
  border-bottom: 1px solid #dcdfe6;
}

.number-up:hover,
.number-down:hover {
  background-color: #e4e7ed;
}

.number-up:active,
.number-down:active {
  background-color: #d3d7de;
}

.custom-number-input.readonly .number-controls {
  display: none;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.blue-button {
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  cursor: pointer;
  height: 36px;
  line-height: 20px;
  min-width: 80px;
}

.red-button {
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  cursor: pointer;
  height: 36px;
  line-height: 20px;
  min-width: 80px;
}

.cancel-button {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  cursor: pointer;
  height: 36px;
  line-height: 20px;
  min-width: 80px;
}

.confirm-button {
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  cursor: pointer;
  height: 36px;
  line-height: 20px;
  min-width: 80px;
}

/* 表格操作按钮样式 */
:deep(.el-button-group) {
  display: flex;
  justify-content: center;
}

:deep(.el-button--link) {
  height: 28px;
  padding: 0 8px;
  font-size: 13px;
}

:deep(.el-button--link.el-button--primary) {
  color: #409eff;
}

:deep(.el-button--link.el-button--danger) {
  color: #f56c6c;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 4px;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  border-top: 1px solid #f0f0f0;
}

/* 按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 0 0;
}

.dialog-footer .el-button {
  margin-left: 0;
}

/* 输入框样式 */
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  height: 40px;
}

:deep(.el-input.is-disabled .el-input__wrapper),
:deep(.el-input.is-readonly .el-input__wrapper) {
  background-color: #f5f7fa;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
  padding-right: 0;
}

:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  border-color: #dcdfe6;
  background-color: #f5f7fa;
}

:deep(.el-input__inner) {
  text-align: left;
}

:deep(.el-input-group__append) {
  background-color: #f5f7fa;
  color: #606266;
  border-color: #dcdfe6;
  padding: 0 12px;
}

/* 表单布局样式 */
.form-item-row {
  display: flex;
  margin-bottom: 24px;
  gap: 20px;
}

.form-item {
  flex: 1;
  position: relative;
}

.form-item.full-width {
  width: 100%;
}

.form-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.form-label .required {
  color: #f56c6c;
  margin-right: 4px;
}

.form-input {
  width: 100%;
}

.dialog-content {
  padding: 30px 20px;
}
</style>
